//
//  WMH_NewsVedioDetail_ViewController.m
//  EpointFrame5
//
//  Created by AndLi on 15/4/7.
//  Copyright (c) 2015年 Epoint. All rights reserved.
//

#import "WMH_NewsVedioDetail_ViewController.h"

//视频播放
#import <MediaPlayer/MPMoviePlayerController.h>
#import <MediaPlayer/MPMoviePlayerViewController.h>

#import "EpointWebInfoDetailAttachModel.h"
#import "Task_GetInfoDetail.h"
#import "NewsAttachModel.h"
#import "EpointAttachDownloadListViewController.h"

#define getNewsDetailTaskId 1

@interface WMH_NewsVedioDetail_ViewController ()<UIWebViewDelegate>
{
    UIWebView *mWebView;
    
    NSString *InfoID;
    NSString *CateNum;
    NSString *IsNeedUrl;
    
    NSString *InfoTitle;
    NSString *ShareUrl;
    NSString *videourl;

    NSMutableArray *attachList;
    
    BOOL clickflag;
}
@end

@implementation WMH_NewsVedioDetail_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    InfoID      = [self.passParam objectForKey:@"InfoID"];
    CateNum     = [self.passParam objectForKey:@"CateNum"];
    IsNeedUrl   = [self.passParam objectForKey:@"IsNeedUrl"];
    
    mWebView = [[UIWebView alloc]initWithFrame:[self getFullContentFrame]];
    mWebView.delegate = self;
    [self.view addSubview:mWebView];
    
    [self getNewsDetailData];
}

#pragma mark 获取新闻详情
- (void)getNewsDetailData
{
    [self showMBPHUD];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:InfoID    forKey:@"InfoID"];
    [params setObject:CateNum   forKey:@"CateNum"];
    [params setObject:IsNeedUrl forKey:@"IsNeedUrl"];
    [params setObject:@"1"      forKey:@"isvideo"];
    [params setObject:@"320"    forKey:@"imgwidth"];
    [self startTask:@"Task_GetInfoDetail" withParams:params withTaskId:getNewsDetailTaskId];
}

#pragma mark 刷新UI
-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    [self hideMBPHUD];//关闭滚动条
    if (taskId==getNewsDetailTaskId) {
        [self dealNewsDetailData:obj];
    }
}

#pragma mark 处事新闻详情数据
-(void)dealNewsDetailData:(NSObject *)obj{
    
    
    //处理异常信息
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        return;
    }
    
    //验证返回串
    // if ([self validateXML:result]) {//校验数据
    NSString *result = [arr objectAtIndex:2];
    
    
    NSString *newscontent_fontsize = [DBFrameService getConfigValue:WMH_NewsContent_FontSize];
    
    //注意：css拼接中使用%%，进行百分号的格式化处理
    NSString * mycss =[NSString stringWithFormat:@"<style>p{margin:0px;padding:0px;}#news_outline {font-family:System;color: #5a5a5a; font-size:14px;text-align:left;padding-bottom:16px;padding-top:4px;}.ParagraphIndent img,p img{width:100%%;max-width:100%%;display:block;margin-bottom: 10px;}.ParagraphIndent,p,P{-webkit-box-sizing:border-box;box-sizing:border-box; width:100%%; padding:0 10px; letter-spacing:0.1px;color:#121212;text-indent:2em;font-size:%@px;line-height:150%%; overflow: hidden;word-wrap:break-word; word-break: bre-all;height:auto;zoom:1;text-align:justify;text-justify:inter-ideograph;padding-left:2px;font-family:System;}#news_title {font-weight:bold;text-align:left;-webkit-box-sizing:border-box;box-sizing:border-box; width:100%%;letter-spacing:0.1px;color:#121212;font-size:20px;line-height:120%%; overflow: hidden;word-wrap:break-word; word-break: bre-all;height:auto;zoom:1;text-align:justify;text-justify:inter-ideograph;font-family:System;padding-right:6px};</style>",newscontent_fontsize];
    
    result =[result stringByReplacingOccurrencesOfString:@"<![CDATA[" withString:@""];
    result= [result stringByReplacingOccurrencesOfString:@"]]>" withString:@""];
    
    videourl            = [EpointStringUtil getXMLFormatedAttribute:result :@"videourl"];
    InfoTitle           = [EpointStringUtil getXMLFormatedAttribute:result :@"title"];
    NSString *infoDate  = [EpointStringUtil getXMLFormatedAttribute:result :@"infodate"];
    ShareUrl            = [EpointStringUtil getXMLFormatedAttribute:result :@"weburl"];//解析链接内容
    
    //处理附件
    if(![[EpointStringUtil getXMLFormatedAttribute:result :@"attachfiles"]isEqualToString:@""]){
        NSString *attachXML = [EpointStringUtil getXMLFormatedAttributeBsWithTag:result xmlTag:@"attachfiles"];
        attachList = [Task_GetInfoDetail getAttachLists:attachXML];
        [self setRightBarButtonItemWithTitle:@"附件" action:@selector(clickAttachButton)];
    }
    
    result              = [EpointStringUtil getXMLFormatedAttribute:result :@"infocontent"];
    
    
    
    
    //对图片URL增加网址
    if([result rangeOfString:@"src=\""].location !=NSNotFound){
        
        result=[result stringByReplacingOccurrencesOfString:@"<img " withString:@"<img  onclick = \"document.location=this.src\" "];
        result=[result stringByReplacingOccurrencesOfString:@"<IMG " withString:@"<IMG  onclick = \"document.location=this.src\" "];
    }
    
    NSString *disContent = [NSString stringWithFormat:@"%@<div id='news_title'>%@</div><div id='news_outline'>%@ %@</div>%@<br />",mycss,InfoTitle,@"",[self dealDate:infoDate],result];
    
    [mWebView loadHTMLString:disContent baseURL:nil];
}

#pragma mark 下载附件(使用框架自带的)
-(void)clickAttachButton{
    NSMutableArray *fileList = [[NSMutableArray alloc]init];
    
    for (NewsAttachModel *m in attachList) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:m.AttFileName forKey:@"FileName"];
        [dic setObject:InfoID        forKey:@"FolderGuid"];
        [dic setObject:m.url         forKey:@"FileUrl"];
        [dic setObject:@"0"          forKey:@"isBigFile"];
        [fileList addObject:dic];
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:fileList forKey:@"FileList"];
    [params setObject:InfoID forKey:@"FolderGuid"];
    EpointAttachDownloadListViewController *v = [[EpointAttachDownloadListViewController alloc]init];
    v.passParam = params;
    [self.navigationController pushViewController:v animated:YES];
}

#pragma 处理日期类型
-(NSString *)dealDate:(NSString *)_infoDate{
    if([_infoDate rangeOfString:@"/"].location!=NSNotFound || [_infoDate rangeOfString:@"-"].location!=NSNotFound){
        NSArray *str = [_infoDate componentsSeparatedByString:@" "];
        NSString *temp = [NSString stringWithFormat:@"%@: %@",@"发布时间",[str objectAtIndex:0]];
        return  temp;
    }else{
        return [NSString stringWithFormat:@"%@: %@",@"发布时间",_infoDate];
    }
}

#pragma mark webview代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString* rurl=[[request URL] absoluteString];
    NSLog(@"%@",rurl);
    if([rurl rangeOfString:@".jpg"].location!=NSNotFound){
        if(videourl !=nil && [videourl rangeOfString:@".mp4"].location!=NSNotFound){
            NSLog(@"%@",videourl);
            [self playMovie:videourl];
            return NO;
        }else{
            [self toastMessage:@"暂不支持此视频的播放，请在电脑端查看!"];
            return NO;
        }
    }
    
    return true;
}

#pragma mark ----------------------播放视频----------------------

-(void)playMovie:(NSString *)videoURL{
    videoURL = [EpointStringUtil URLEncodedString:videoURL];
    NSURL *url = [NSURL URLWithString:videoURL];
    
    MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    movie.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    [movie.view setFrame:CGRectMake(0, -20, 320, 480)];
    movie.moviePlayer.initialPlaybackTime = -1;
    [self presentViewController:movie animated:YES completion:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didFinishPlay:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:movie];
    [movie.moviePlayer play];
}


- (void)didFinishPlay:(NSNotification *)notification {
    NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
    MPMoviePlayerController* theMovie = [notification object];
    switch ([reason intValue]) {
        case MPMovieFinishReasonPlaybackEnded:{
            NSLog(@"playbackFinished. Reason: Playback Ended");
            [theMovie.view removeFromSuperview];
        }
            break;
        case MPMovieFinishReasonPlaybackError:{
            NSLog(@"playbackFinished. Reason: Playback Error");
            [theMovie.view removeFromSuperview];
        }
            break;
        case MPMovieFinishReasonUserExited:{
            NSLog(@"playbackFinished. Reason: User Exited");
            [theMovie.view removeFromSuperview];
            break;
        }
        default:
            break;
    }
}


//<?xml version="1.0" encoding="gb2312" ?>
//<EpointDataBody>
//<DATA>
//<ReturnInfo>
//<Status>True</Status>
//<Description></Description>
//</ReturnInfo>
//<UserArea>
//<title><![CDATA[身边这点事]]></title>
//<infodate>2013-07-30 01:00</infodate>
//<infotype>News</infotype>
//<clicktimes>0</clicktimes>
//<infocontent><![CDATA[<img src="http://192.168.200.159/WebBuilderMobileService/Upfiles/FileAttach/826081f7-f463-401c-9214-0a79e281d8db/microvideoplay_Small_shenbian.jpg"/>]]></infocontent>
//<weburl><![CDATA[http://demo.epoint.com.cn:1616/EWB804Test/xwzx/20130730/002002004_0d63c7d9-650c-4fe7-9480-a610e0476616.htm]]></weburl>
//                 <attachfiles>
//                 <SingleFile>
//                 <AttFileName><![CDATA[Wildlife.mp4]]></AttFileName>
//                 <url><![CDATA[http://192.168.200.159/EpointBigFileUpLoad/BigFileUpLoadStorage/d6acb7e1-37ce-465a-bc3e-4ec96dd76792/Wildlife.mp4]]></url>
//                               </SingleFile>
//                               </attachfiles>
//                               <videourl>http://192.168.200.159/EpointBigFileUpLoad/BigFileUpLoadStorage/d6acb7e1-37ce-465a-bc3e-4ec96dd76792/Wildlife.mp4
//                               </videourl>
//                               </UserArea>
//                               </DATA>
//                               </EpointDataBody>



@end
